/*************************************************************************
	> File Name: my_cat.c
	> Author: 
	> Mail: 
	> Created Time: Wed 23 Sep 2020 02:42:09 PM CST
 ************************************************************************/

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<ctype.h>

int isSpaceLine(char* buf, int len);
void normalOut(FILE* file, char* buf, int len);
void lineOut(FILE* file, char* buf, int len);
void noSpaceLineOut(FILE* file, char* buf, int len);


int main(int argc, char** argv){
    int flag = 0;
    char opt;
    char filename[256];

    while ((opt = getopt(argc, argv, "nb")) != -1){
        switch(opt){
            case 'n':
            if(flag == 0){
                flag = 1;
            }
                break;
            case 'b':
                flag = 2;
                break;
            default:
                fprintf(stderr, "Usage: %s [-nb] filename\n", argv[0]);           
                exit(EXIT_FAILURE);
                break;
        }
    }
    
    if(optind > argc){
        fprintf(stderr, "please input the filename you want to read\n");
        exit(EXIT_FAILURE);
    }

    
    char buf[20];
    memset(buf, 0, 20);
    
    while(optind < argc){
        strcpy(filename, argv[optind]);
        optind++;
        FILE* file = fopen(filename, "r");
        if(file == NULL){
            fprintf(stderr, "Failed to open file %s\n", filename);
            exit(EXIT_FAILURE);
        }

        if(flag == 0){
            normalOut(file, buf, 20);    
        }
        else if(flag == 1){
            lineOut(file, buf, 20);
        }
        else{
            noSpaceLineOut(file, buf, 20);
        }
        fclose(file);
        fprintf(stdout, "--------------------------------------------------------------------------------\n");
    }
    return 0;
}

int isSpaceLine(char* buf, int len){
    int pos = 0;
    while(pos < len && buf[pos] != '\n'){
        if(!isspace(buf[pos])){
            return 0;    
        }
        pos++;
    }
    return 1;
}

void normalOut(FILE* file, char* buf, int len){
    while((fgets(buf, len, file)) != NULL){
        fputs(buf, stdout);
    }
    return;
}


void lineOut(FILE* file, char* buf, int len){
    int num = 1;
    while((fgets(buf, len, file)) != NULL){
        fprintf(stdout, "%d\t", num);
        num++;
        fputs(buf, stdout);
    }    
    return;
}


void noSpaceLineOut(FILE* file, char* buf, int len){
    int num = 1;
    while((fgets(buf, len, file)) != NULL){
        if(isSpaceLine(buf, len) == 1){
           fprintf(stdout, "\t"); 
        }
        else{
            fprintf(stdout, "%d\t", num);
            num++;
        }
        fputs(buf, stdout);
    }
    return;
}
